package com.wocai.jrt.orgadmin.employee.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.vteba.cache.redis.RedisService;
import com.vteba.utils.common.PropsUtils;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.vteba.web.editer.StringEditor;
import com.wocai.jrt.admin.user.model.Roles;
import com.wocai.jrt.admin.user.service.spi.RolesService;
import com.wocai.jrt.orgadmin.employee.bean.SendVerificationBean;
import com.wocai.jrt.orgadmin.employee.model.Employee;
import com.wocai.jrt.orgadmin.employee.model.EmployeeBean;
import com.wocai.jrt.orgadmin.employee.model.EmployeeBean.Criteria;
import com.wocai.jrt.orgadmin.employee.service.spi.EmployeeService;
import com.wocai.jrt.orgadmin.utils.SmsUtils;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 员工权限控制器
 * @author yinlei
 * @date 2015-8-4 15:49:29
 */
@Controller
@RequestMapping("/userAuth")
public class UserAuthAction extends GenericAction<Employee> {
	private static final Logger LOGGER = LoggerFactory.getLogger(UserAuthAction.class);
	
	@Inject
	private EmployeeService employeeServiceImpl;
	@Inject
	private RedisService<String, String> redisService;
	@Inject
	private RolesService rolesServiceImpl;
	
	public static final String CHECK_SMS_EMP_SET_AUTHORTIES= "check_sms_emp_set_authorties";
	/**
     * 获得员工List，初始化列表页。
     * @param model 参数
     * @return 员工List
     */
    @RequestMapping("/list")
    public String list(Employee model, Map<String, Object> maps) {
        return "userAuth/list";
    }
	
    @ResponseBody
    @RequestMapping("/query")
    public Map<String, Object> query(@RequestBody Employee user) {
    	Map<String, Object> result = new HashMap<String, Object>();
    	try {
    		EmployeeBean params = new EmployeeBean();
    		Criteria criteria = params.createCriteria();
    		// 工号
    		if (StringUtils.isNotBlank(user.getEmployeeNo())) {
    			criteria.andEmployeeNoLike(user.getEmployeeNo());
    		}
    		// 姓名
    		if (StringUtils.isNotBlank(user.getName())) {
    			criteria.andNameLike(user.getName());
    		}
    		// 机构id
    		criteria.andOrgIdEqualTo(UserUtils.getOrgId());
    		
    		List<Employee> list = employeeServiceImpl.pagedForList(params);
    		
    		if (LOGGER.isInfoEnabled()) {
    			LOGGER.info("query employee success, will query user's roles.");
    		}
    		
    		// 一对多，展示成1对1，蛋疼
    		List<String> empIdList = new ArrayList<>();
    		for (Employee employee : list) {
    			empIdList.add(employee.getEmployeeId());
    		}
    		List<Roles> rolesList = employeeServiceImpl.queryUserRoles(empIdList);
    		if (LOGGER.isInfoEnabled()) {
    			LOGGER.info("query User's roles , will match user's roles.");
    		}
    		// 匹配用户和他的角色
    		for (Employee employee : list) {
    			String employeeId = employee.getEmployeeId();
    			for (Roles roles : rolesList) {
    				if (employeeId.equals(roles.getRoleDesc())) {
    					// 使用这个字段来存放角色，还是要放到这个位置，因为可能被更新
    					String roleIds = employee.getRoleIds();
    					if (roleIds == null) {
    						employee.setRoleIds(roles.getRoleName());
    					} else {
    						employee.setRoleIds(roleIds + "," + roles.getRoleName());
    					}
    				}
    			}
    		}
    		if (LOGGER.isInfoEnabled()) {
    			LOGGER.info("match user's roles success.");
    		}
    		// 统计的时候，不需要分页
    		params.setStart(null);
    		long totalRecord = employeeServiceImpl.count(params);
    		
    		if (LOGGER.isDebugEnabled()) {
    			LOGGER.debug("user query success.");
    		}
    		
    		// jQuery datatable 就是这样的参数，阿西吧
    		result.put("aaData", list); // 返回的数据
    		result.put("iTotalRecords", totalRecord); // 总记录数
    		result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("user query error, msg=[{}]", e.getMessage());
		}
        return result;
    }
	
    /**
     * 跳转到编辑用户页面
     * @param model 查询参数，携带ID
     * @return Json数据
     */
    @ResponseBody
    @RequestMapping("/edit")
    public Employee edit(Employee model) {
    	String userId = model.getId();
    	if (StringUtils.isBlank(userId)) {
    		LOGGER.error("params userId cannot be null.");
    		return null;
    	}
    	try {
    		model = employeeServiceImpl.get(userId);
		} catch (Exception e) {
			LOGGER.error("edit user, get user error, userId=[{}], msg=[{}].", userId, e.getMessage());
		}
        return model;
    }
    
    /**
     * 更新员工角色信息
     * @param model 要更新的员工信息，含有ID和角色信息
     * @return 操作结果信息
     */
    @ResponseBody
    @RequestMapping("/update")
    public JsonBean update(@RequestBody Employee model) {
    	JsonBean bean = new JsonBean();
    	if (StringUtils.isBlank(model.getEmployeeId())) {
    		bean.setMessage("update Employee, employeeId cannot be null.");
    		return bean;
    	}
    	try {
    		int result = employeeServiceImpl.setUserRole(model);
            if (result == 1) {
                bean.setMessage(SUCCESS);
                bean.setCode(1);
                LOGGER.info("update record success.");
            } else {
                bean.setMessage(ERROR);
                LOGGER.error("update record error.");
            }
		} catch (Exception e) {
			LOGGER.error("update record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
        return bean;
    }
    
    /**
     * 发送更改角色验证码
     * @param model 要更新的员工信息，含有ID和角色信息
     */
    @ResponseBody
    @RequestMapping("/sendverification")
    public JsonBean sendverification(@RequestBody SendVerificationBean bean) {
		JsonBean json = new JsonBean();
		// 入参检验
		if (StringUtils.isAnyBlank(bean.getRoleIds())) {
			json.setCode(2);
			json.setMessage("没有权限修改！");
			return json;
		}
		String[] roleList = bean.getRoleIds().split(",");
		List<Roles> rolesList = new ArrayList<Roles>();
		Set<String> mobileMap = new HashSet<String>();
		for (String string : roleList) {
			Roles model = rolesServiceImpl.get(string);
			String mobile = model.getComMobile();
			if(!mobileMap.contains(mobile)){
				mobileMap.add(mobile);
				Employee emp = employeeServiceImpl.get(bean.getEmployeeId());
				if(StringUtils.isBlank(mobile)){
					LOGGER.info("employee sendverification for modify roles error.");
				}else{
					// 业务
					try {
						rolesList.add(model);
						String smsContent = PropsUtils.get("sms.empSetAuthorties");

						String authCode = null;
						authCode = redisService.get(CHECK_SMS_EMP_SET_AUTHORTIES + mobile);
						if (null == authCode) {
							authCode = (int) (Math.random() * 9000 + 1000) + "";
							int smsTimeout = PropsUtils.getInt("sms.timeout");// 这里是分钟为单位
							redisService.set(CHECK_SMS_EMP_SET_AUTHORTIES + mobile, authCode,
									smsTimeout * 60);
						}
						smsContent = smsContent.replaceFirst("operater", UserUtils.getUser().getName());
						smsContent = smsContent.replaceFirst("alloter", emp.getName());
						smsContent = smsContent.replaceFirst("rolename", model.getRoleName());
						smsContent = smsContent.replaceFirst("#", authCode);
						String result = SmsUtils.send(mobile, smsContent);
						if (result.startsWith("true")) {
							json.setCode(1);
							json.setMessage(SUCCESS);
						} else {
							json.setCode(0);
							json.setMessage(result);
						}
					} catch (Exception e) {
						LOGGER.error("employee sendverification for modify roles, errorMsg=[{}].", e.getMessage());
						json.setCode(0);
						json.setMessage(ERROR);
					}
				}
			}
		}
		if(rolesList.size() == 0){
			json.setCode(2);
			json.setMessage("没有权限修改！");
		}
		json.setData(rolesList);
		return json;
	}
    
    /**
     * 验证修改角色权限验证码
     */
    @ResponseBody
    @RequestMapping("/verifyCode/{json}")
    public JsonBean verifyCode(@PathVariable String json) {
    	JsonBean bean = new JsonBean();
    	bean.setCode(1);
    	if (StringUtils.isBlank(json)) {
    		bean.setCode(0);
    		bean.setMessage("update Employee, employeeId cannot be null.");
    		return bean;
    	}
    	try {
    		Map<String, Object> mapJson  = JSONObject.parseObject(json);
    		for (Entry<String, Object> entry : mapJson.entrySet()) {  
    			String authCode = redisService.get(CHECK_SMS_EMP_SET_AUTHORTIES + entry.getKey());
    			String v = (String)entry.getValue();
    			if (null == authCode) {
    				bean.setCode(0);
    				bean.setMessage("验证码已过期，请重新获取验证码！");
    				return bean;
    			}
    			if (!(v.equals(authCode))) {
    				bean.setCode(0);
    				bean.setMessage("验证码错误！");
    				return bean;
    			}
    		}  
		} catch (Exception e) {
			LOGGER.error("update record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
        return bean;
    }
    
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
    	// 空字符串转换为null
        binder.registerCustomEditor(String.class, new StringEditor());
    }
}
